The Mechanics of State
Okay, so we have just seen the power of state by using the useState function, but now let’s get a better understanding of how exactly state works in React.
And let’s start from a fundamental React principle that we have already discussed earlier.
So remember how we learned that in React we do not manipulate the DOM directly when we want to update a component’s view, right? So React is declarative, not imperative, and so we never touch the DOM in our code.
But if that’s the case, then this leads us to the question of, how do we update the component on the screen whenever some data changes or whenever we need to respond to some event like a click?
Now, we already know that the answer to this question is state, but here we are trying to derive it from first principles. So anyway, to answer that question, we need to understand another fundamental React principle, which is the fact that React updates a component view by re-rendering that entire component whenever the underlying data changes.
Now, as soon as we will reach the section about how React works behind the scenes, we will learn exactly what actually happens inside React when a component re-renders. But for now, just know that re-rendering basically means that React calls the component function again, so each time the component is rendered.
So conceptually we can imagine this as React removing the entire view and replacing it with a new one each time a re-render needs to happen. But again, we will learn exactly what happens later. Now, React preserves the component state throughout re-renders, and so even though a component can be rendered and re-rendered time and time again, the state will not be reset unless the component disappears from the UI entirely, which is what we call unmounting.
Now speaking of state, it is when state is updated that a component is automatically re-rendered. So let’s imagine that there is an event handler in the view, for example, on a button that the user can click.